<template>
    <div>
      <h3>欢迎, {{ userInfo.nickname }}!</h3>
      <div class="chat-container">
        <div class="messages">
          <div v-for="message in messages" :key="message.id" class="message">
            <strong>{{ message.user }}:</strong> {{ message.text }}
          </div>
        </div>
        <el-input v-model="newMessage" placeholder="输入消息" @keyup.enter="sendMessage"></el-input>
        <el-button @click="sendMessage">发送</el-button>
      </div>
    </div>
</template>

<script>
import {sendChat, getChat} from "../api/tournament";
export default {
  name: "ChatRoom",
  data() {
    return {
      userInfo: {"nickname": ""},
      messages: [],
      newMessage: ''
    };
  },
  methods: {
    async sendMessage() {
      if (this.newMessage.value.trim() === '') return;

      // 模拟发送消息
      const message = {
        id: this.messages.length + 1,
        user: this.userInfo.nickname || '用户',
        text: this.newMessage,
      };
      await sendChat(message)
    },

    async fetchMessages() {
      const params = {
        date: this.lastFetchDate || new Date().toISOString() // 如果没有lastFetchDate则使用当前时间
      };
      const response = await getChat(params);
      this.messages = response.data.messages;
      if (this.messages.length) {
        this.lastFetchDate = this.messages[0].timestamp; // 更新最后获取消息的时间
      }
    },
  },

  mounted() {
    this.fetchMessages(); // 初始化时获取消息
    this.messageInterval = setInterval(this.fetchMessages, 2000); // 每2秒获取一次消息
  },
  beforeDestroy() {
    clearInterval(this.messageInterval); // 清除定时器
  }
};
</script>

<style scoped>
.message {
  margin-bottom: 5px;
}
</style>
